import requests
from lxml import etree


class Lmonkey():
    # 登录请求地址
    loginurl = 'https://www.lmonkey.com/login'
    # 账号中心地址
    orderurl = 'https://www.lmonkey.com/my/order'

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'
    }
    req = None
    token = 0
    def __init__(self):

        # 利用session 获取请求对象
        self.req = requests.session()
        
        if  self.getLogin():
            if self.postLogin():
                self.getOrder()
    #请求登录 拿到token
    def getLogin(self):

        res = self.req.get(url=self.loginurl, headers=self.headers)
        if res.status_code == 200:
            print('请求登录成功')
            html = etree.HTML(res.text)
            self.token = html.xpath('//input[@name="_token"]/@value')
            print(self.token)
            return True
    #post发送token 和账号密码
    def postLogin(self):
        data = {
            '_token': self.token,
            'username': '17610195211',
            'password': 'yichuan123'
        }
        res=self.req.post(url=self.loginurl,data=data,headers=self.headers)
        if res.status_code==200 or res.status_code==302:
            print('登录成功')
            return True

    #进入账户中心 获取订单编号
    def getOrder(self):
        res=self.req.get(url=self.orderurl,headers=self.headers)
        if res.status_code==200:
            print('获取订单成功')
            html=etree.HTML(res.text)
            r=html.xpath('//small[@class="d-block text-muted font-weight-bold"]/text()')
            for i in r:
                print(i.strip())
obj = Lmonkey()


# 1.请求登录页面
# 2.获取token 请求登录
# 3.请求订单
